#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

int main()
{
    Mat image = imread("/home/lwj/opencv.21/cz.png", IMREAD_COLOR); // 读取图像

    Mat gray;
    cvtColor(image, gray, COLOR_BGR2GRAY); // 转换为灰度图像

    Mat edges;
    Canny(gray, edges, 50, 150); // 检测边缘

    vector<vector<Point>> contours;
    findContours(edges, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); // 寻找轮廓

    // 对每个轮廓计算最小外接旋转矩形
    for (int i = 0; i <contours.size(); i++)
    {
        RotatedRect rect = minAreaRect (contours[i]);

        // 绘制外接旋转矩形
        Point2f vertices[4];
        rect.points(vertices);
        for (int j = 0 ;j < 4; j++)
        {
         line(image,vertices[j], vertices[(j + 1) % 4], cv::Scalar(0, 255, 0), 2);
        }
    }

    cv::imshow("Image with Rotated Rectangles", image);
    cv::waitKey(0);

    return 0;

    waitKey(0);
    return 0;
}